package com.tdu.spider.biz.service.jike;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.tdu.spider.biz.service.jike.vo.JikeResultVO;
import com.tdu.spider.biz.service.jike.vo.JikeSourceVO;
import com.tdu.spider.biz.service.jike.vo.MessageQueryVO;
import com.tdu.spider.biz.service.same.vo.CommonResult;
import com.tdu.spider.biz.util.HttpUtils;
import com.tdu.spider.model.JkCategoryDO;
import com.tdu.spider.model.JkMessageDO;
import com.tdu.spider.model.JkTopicDO;
import com.tdu.spider.model.JkUserInfoDO;
import org.apache.http.Header;
import org.apache.http.client.CookieStore;
import org.apache.http.client.fluent.Executor;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.fluent.Response;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.cookie.BasicClientCookie2;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.Args;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

@Service
public class JikeApiService {
    private static Logger       logger  = LoggerFactory.getLogger(JikeApiService.class);

    private static List<Header> headers = Lists.newArrayList();

    static {
        headers.add(new BasicHeader("App-BuildNo", "742"));
        headers.add(new BasicHeader("OS", "ios"));
        headers.add(new BasicHeader("App-Version", "3.3.1"));
        headers.add(new BasicHeader("Accept", "*/*"));
        headers.add(new BasicHeader("Content-Type", "application/json"));
        headers.add(new BasicHeader("Accept-Language", "zh-cn"));
        headers.add(new BasicHeader("User-Agent", "即刻/742 CFNetwork/811.5.4 Darwin/16.6.0"));
        headers.add(new BasicHeader("Manufacturer", "Apple"));
        headers.add(new BasicHeader("OS-Version", "Version 10.3.2 (Build 14F89)"));
        headers.add(new BasicHeader("Model", "iPhone8,1"));
        headers.add(new BasicHeader("Cookie",
            "jike:recommendfeed:latestRecCreatedAt=2017-06-12T12:57:01.410Z; jike:sess=eyJfdWlkIjoiNTkzZThkMDc1NjI1MzcwMDEyYzIwYmNlIiwiX3Nlc3Npb25Ub2tlbiI6ImpPSXAyNDZSWkFzUWl3enh2d2lGZWxzMDEifQ==; jike:sess.sig=YGiym8Q165EpU5W01lWpqdIh_ho"));
    }

    private CookieStore buildCookieStore() {
        CookieStore store = new BasicCookieStore();
        BasicClientCookie2 cookie1 = new BasicClientCookie2("jike:recommendfeed:latestRecCreatedAt",
            "2017-06-05T10:08:52.733Z");
        cookie1.setDomain("app.jike.ruguoapp.com");
        BasicClientCookie2 cookie2 = new BasicClientCookie2("jike:sess",
            "eyJfdWlkIjoiNTkyZjc3ZjMzYWI0YTUwMDEzM2M4YjgwIiwiX3Nlc3Npb25Ub2tlbiI6ImxDMURlMGx5M1h0bHVtV1d0WGVCd09HWDQifQ==");
        cookie2.setDomain("app.jike.ruguoapp.com");
        BasicClientCookie2 cookie3 = new BasicClientCookie2("jike:sess.sig",
            "bJA86Zx0XxTBCqEsZzi3P-0ac3Q");
        cookie3.setDomain("app.jike.ruguoapp.com");

        store.addCookie(cookie1);
        store.addCookie(cookie2);
        store.addCookie(cookie3);
        return store;
    }

    public List<JkMessageDO> queryMessage(MessageQueryVO messageQueryVO) throws Exception {
        String url = "https://app.jike.ruguoapp.com/1.0/users/messages/history";
        Map<String, Object> params = Maps.newHashMap();
        params.put("topic", messageQueryVO.getTopic());
        params.put("limit", messageQueryVO.getLimit());
        if (messageQueryVO.getMessageIdLessThan() != null) {
            params.put("messageIdLessThan", messageQueryVO.getMessageIdLessThan());
        }
        StringEntity stringEntity = new StringEntity(JSON.toJSONString(params));
        stringEntity.setContentType("text/json");
        Request request = Request.Post(url).setHeaders(headers.toArray(new Header[] {}))
            .body(stringEntity);
        Response response = Executor.newInstance(HttpUtils.httpClient()).use(buildCookieStore())
            .execute(request);
        String content = response.returnContent().asString();
        //logger.info("queryMessage url:{},params:{},result:{}", messageQueryVO, content);

        if (StringUtils.hasLength(content)) {
            CommonResult<List<JkMessageDO>> result = JSON.parseObject(content,
                new TypeReference<CommonResult<List<JkMessageDO>>>() {
                });
            return result.getData();
        }
        return Lists.newArrayList();
    }

   
    public List<JkTopicDO> recommendFeed() throws Exception {
        String url = "https://app.jike.ruguoapp.com/1.0/recommendFeed/list";
        Request request = Request.Get(url).setHeaders(headers.toArray(new Header[] {}));
        Response response = Executor.newInstance(HttpUtils.httpClient()).execute(request);
        String content = response.returnContent().asString();
        logger.info("recommendFeed url:{},params:{},result:{}", "", content);

        if (StringUtils.hasLength(content)) {
            CommonResult<List<JkTopicDO>> result = JSON.parseObject(content,
                new TypeReference<CommonResult<List<JkTopicDO>>>() {
                });
            return result.getData();
        }
        return Lists.newArrayList();
    }

   
    public JkTopicDO getTopic(String messageId) throws Exception {
        String url = "https://app.jike.ruguoapp.com/1.0/topics/get?id=" + messageId
                     + "&ref=NEWS_FEED_RECOMMEND_MESSAGE";
        Request request = Request.Get(url).setHeaders(headers.toArray(new Header[] {}));
        Response response = Executor.newInstance(HttpUtils.httpClient()).execute(request);
        String content = response.returnContent().asString();
        logger.info("getTopic url:{},params:{},result:{}", messageId, content);

        if (StringUtils.hasLength(content)) {
            CommonResult<JkTopicDO> result = JSON.parseObject(content,
                new TypeReference<CommonResult<JkTopicDO>>() {
                });
            return result.getData();
        }
        return null;
    }

   
    public JikeSourceVO getMediaMeta(String messageId) throws Exception {
        String url = "https://app.jike.ruguoapp.com/1.0/misc/getMediaMeta?message=" + messageId;
        Request request = Request.Get(url).setHeaders(headers.toArray(new Header[] {}));
        Response response = Executor.newInstance(HttpUtils.httpClient()).execute(request);
        String content = response.returnContent().asString();
        logger.info("getMediaMeta url:{},params:{},result:{}", messageId, content);

        if (StringUtils.hasLength(content)) {
            CommonResult<JikeSourceVO> result = JSON.parseObject(content,
                new TypeReference<CommonResult<JikeSourceVO>>() {
                });
            return result.getData();
        }
        return null;
    }

   
    public List<JkTopicDO> getMyTopic(Integer skip) throws Exception {
        String url = "https://app.jike.ruguoapp.com/1.0/users/topics/listSubscribed?limit=20&skip="
                     + skip + "&sortBy=SUBSCRIBE_TIME";
        Request request = Request.Get(url).setHeaders(headers.toArray(new Header[] {}));
        Response response = Executor.newInstance(HttpUtils.httpClient()).execute(request);
        String content = response.returnContent().asString();
        logger.info("getMyTopic url:{},params:{},result:{}", "", content);

        if (StringUtils.hasLength(content)) {
            CommonResult<List<JkTopicDO>> result = JSON.parseObject(content,
                new TypeReference<CommonResult<List<JkTopicDO>>>() {
                });
            return result.getData();
        }
        return null;
    }

   
    public List<JkTopicDO> queryTopic(Integer categoryId, Integer skip) throws Exception {
        String url = "https://app.jike.ruguoapp.com/1.0/users/topics/list?categoryId=" + categoryId
                     + "&limit=20&skip=" + skip;
        Request request = Request.Get(url).setHeaders(headers.toArray(new Header[] {}));
        Response response = Executor.newInstance(HttpUtils.httpClient()).execute(request);
        String content = response.returnContent().asString();
        logger.info("queryTopic url:{},params:{},result:{}", "", content.substring(0, 100));

        if (StringUtils.hasLength(content)) {
            CommonResult<List<JkTopicDO>> result = JSON.parseObject(content,
                new TypeReference<CommonResult<List<JkTopicDO>>>() {
                });
            return result.getData();
        }
        return null;
    }

   
    public List<JkCategoryDO> getCategory() throws Exception {
        String url = "https://app.jike.ruguoapp.com/1.0/categories/list";
        Request request = Request.Get(url).setHeaders(headers.toArray(new Header[] {}));
        Response response = Executor.newInstance(HttpUtils.httpClient()).execute(request);
        String content = response.returnContent().asString();
        logger.info("getCategory url:{},params:{},result:{}", "", content);

        if (StringUtils.hasLength(content)) {
            CommonResult<List<JkCategoryDO>> result = JSON.parseObject(content,
                new TypeReference<CommonResult<List<JkCategoryDO>>>() {
                });
            return result.getData();
        }
        return null;
    }

   
    public JkUserInfoDO getUserInfo() throws Exception {
        String url = "https://app.jike.ruguoapp.com/1.0/users/profile";
        Request request = Request.Get(url).setHeaders(headers.toArray(new Header[] {}));
        Response response = Executor.newInstance(HttpUtils.httpClient()).execute(request);
        String content = response.returnContent().asString();
        logger.info("getUserInfo url:{},params:{},result:{}", "", content);

        if (StringUtils.hasLength(content)) {
            return JSON.parseObject(content, JkUserInfoDO.class);
        }
        return null;
    }

   
    public boolean subscribedTopic(String id) throws Exception {
        String url = "https://app.jike.ruguoapp.com/1.0/users/topics/changeSubscriptionStatus";
        Map<String, Object> params = Maps.newHashMap();
        params.put("topicObjectId", id);
        params.put("subscribed", true);
        params.put("push", false);
        params.put("ref", "CATEGORIES_MORE");
        StringEntity stringEntity = new StringEntity(JSON.toJSONString(params));
        stringEntity.setContentType("text/json");
        //stringEntity.setContentEncoding("UTF-8");
        Request request = Request.Post(url).setHeaders(headers.toArray(new Header[] {}))
            .body(stringEntity);
        Response response = Executor.newInstance(HttpUtils.httpClient()).use(buildCookieStore())
            .execute(request);
        String content = response.returnContent().asString();
        logger.info("subscribedTopic url:{},params:{},result:{}", url, id, content);

        if (StringUtils.hasLength(content) && content.contains("subscribedTime")) {
            return true;
        }
        return false;
    }

   
    public boolean createUser(String name, String nick, String password) throws Exception {
        Args.notNull(name, "name");
        Args.notNull(nick, "nick");
        Args.notNull(password, "password");

        //step1:先注册用户
        String url = "https://app.jike.ruguoapp.com/1.0/users/setUsernameAndPassword";
        Map<String, Object> params = Maps.newHashMap();
        params.put("username", "hexiehao123");
        params.put("password", "hexiehao123-");
        StringEntity stringEntity = new StringEntity(JSON.toJSONString(params));
        stringEntity.setContentType("text/json");
        Request request = Request.Post(url).setHeaders(headers.toArray(new Header[] {}))
            .body(stringEntity);
        Response response = Executor.newInstance(HttpUtils.httpClient())
            .execute(request);
        String content = response.returnContent().asString();
        logger.info("setUsernameAndPassword url:{},params:{},result:{}", url, name, password,
            content);
        JikeResultVO resultVO = JSON.parseObject(content, JikeResultVO.class);
        if (resultVO == null || !resultVO.getSuccess()) {
            return false;
        }
        //step2:修改昵称
        url = "https://app.jike.ruguoapp.com/1.0/users/editProfile";
        params = Maps.newHashMap();
        params.put("screenName", name);
        stringEntity = new StringEntity(JSON.toJSONString(params));
        stringEntity.setContentType("text/json");
        request = Request.Post(url).setHeaders(headers.toArray(new Header[] {})).body(stringEntity);
        response = Executor.newInstance(HttpUtils.httpClient()).use(buildCookieStore()).execute(request);
        content = response.returnContent().asString();
        logger.info("editProfile url:{},params:{},result:{}", url, nick, content);
        resultVO = JSON.parseObject(content, JikeResultVO.class);
        if (resultVO == null || !resultVO.getSuccess()) {
            return false;
        }
        return true;
    }
}
